<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Api\Service\Account\WalletService;
use App\Fastapp\Listener\Event\WalletAddBalanceEvent;
use App\Fastapp\Model\AccountWallet;
use App\Fastapp\Model\AccountWalletLog;
use App\Fastapp\Model\FastappChannel;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 钱包列表Mapper类
 */
class FastappAccountWalletMapper extends AbstractMapper
{
    /**
     * @var AccountWallet
     */
    public $model;

    public function assignModel()
    {
        $this->model = AccountWallet::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        // 用户id
        if (isset($params['user_id']) && filled($params['user_id'])) {
            $query->where('user_id', 'like', '%' . $params['user_id'] . '%');
        }

        // 币种id
        if (isset($params['currency_id']) && filled($params['currency_id'])) {
            $query->where('currency_id', '=', $params['currency_id']);
        }

        $admin_id = user()->getId();
        if (!user()->isAdminRole() && $admin_id != env('SUPER_ADMIN')) {
            $roles = array_column(user()->getUserRole(), 'code');
            if (in_array('channel', $roles)) $query->where('channel', FastappChannel::query()->where(['admin_id' => $admin_id])->value('id'));
            else $query->where('id', 0);
        }
        return $query;
    }

    public function recharge(array $params): bool
    {
        $md = AccountWallet::query()->where(['id' => $params['id']])->firstOrFail();
        $ord = [
            'user_id' => $md->user_id,
            'symbol' => $md->symbol,
            'amount' => $params['amount'],
            'object_id' => user()->getId(),
        ];
        if ($params['type'] == 1) {
            $ord['type'] = AccountWalletLog::RECHARGE;
            $ord['object_type'] = AccountWalletLog::OBJ_TYPE_ADMIN;
            WalletService::inc($ord, field: $params['field']);
            api_dispatch(new WalletAddBalanceEvent($md->user_id, (int)get_user_cache('type', $md->user_id), floatval($ord['amount']), $params['field']));
        } else {
            $ord['type'] = AccountWalletLog::USE_BALANCE;
            $ord['object_type'] = AccountWalletLog::OBJ_TYPE_ADMIN;
            WalletService::dec($ord, field: $params['field']);
            api_dispatch(new WalletAddBalanceEvent($md->user_id, (int)get_user_cache('type', $md->user_id), floatval($ord['amount']), $params['field'], 2));
        }
        return true;
    }
}